import { createStore, Commit } from 'vuex'
import { testColumns, testPosts } from './testData'
import { GlobalDataProps, GlobalErrorProps, currentUser } from './type'
import axios from '../libs/http'
import { StorageType, StorageHandler } from '../libs/storage'

// 使用 localStorage
const storageType = StorageType.Local
const storageHandler = new StorageHandler()

// 使用 async 和 await 改造异步请求
const getAndCommit = async (url: string, mutationName: string, commit: Commit) => {
  const { data } = await axios.get(url)
  commit(mutationName, data)
  return data
}
// 真实数据 登录 用post
const postAndCommit = async (url: string, mutationName: string, commit: Commit, payload: any) => {
  const { data } = await axios.post(url, payload)
  commit(mutationName, data)
  return data
}
// store
const store = createStore<GlobalDataProps>({
  state: {
    error: { status: false },
    token: storageHandler.getItem(storageType, 'token') || '',
    loading: false,
    columns: testColumns,
    posts: testPosts,
    user: currentUser
  },
  mutations: {
    login (state, rawData) {
      const { token } = rawData.data
      console.log(rawData.data)
      storageHandler.setItem(storageType, 'token', token)
      axios.defaults.headers.common.Authorization = `Bearer ${token}`
    },
    logout (state) {
      state.token = ''
      storageHandler.remove(storageType, 'token')
      delete axios.defaults.headers.common.Authorization
    },
    setError (state, e: GlobalErrorProps) {
      state.error = e
    },
    fetchCurrentUser (state, rawData) {
      console.log('fetchCurrentUser', rawData.data)
      state.user = { isLogin: true, ...rawData.data }
    },
    createPost (state, newPost) {
      state.posts.push(newPost)
    },
    fetchColumns (state, rawData) {
      state.columns = rawData
    },
    fetchPosts (state, rawData) {
      state.posts = rawData
    },
    setLoading (state, status) {
      state.loading = status
    }
  },
  // 异步
  actions: {
    fetchColumns ({ commit }) {
      return getAndCommit('/testColumns', 'fetchColumns', commit)
    },
    fetchPosts ({ commit }) {
      return getAndCommit('/testPosts', 'fetchPosts', commit)
    },
    login ({ commit }, payload) {
      return postAndCommit('/login', 'login', commit, payload)
    },
    fetchCurrentUser ({ commit }) {
      return getAndCommit('/current', 'fetchCurrentUser', commit)
    },
    // 登录并获取用户信息  先执行login 再执行fetchCurrentUser
    loginAndFetch ({ dispatch }, loginData) {
      return dispatch('login', loginData).then(() => {
        return dispatch('fetchCurrentUser')
      })
    },
    createPost ({ commit }, payload) {
      return postAndCommit('posts', 'createPost', commit, payload)
    }
  },
  // 类似计算属性
  getters: {
    // 根据id找 对应的专栏
    getColumnById: (state) => (id: number) => {
      return state.columns.find(c => c.id === id)
    },
    // 根据columnId找 多个文章
    getPostsByCid: (state) => (cid: number) => {
      return state.posts.filter(post => post.columnId === cid)
    }
  }
})

export default store
